// Copyright 2024 Tvux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package _169

// majorityElement
// 摩尔投票算法
// 其实没有什么，主要就是一点，对拼消耗，因为必存在众数，所以不一样的就对拼消耗掉，最终剩下的就是众数。
func majorityElement(nums []int) int {
	count := 0           // 当前候选众数的“兵力”
	candidate := nums[0] // 候选众数
	for _, num := range nums {
		if num == candidate {
			count++
		} else {
			count--
		}
		if count == 0 {
			candidate = num
			count = 1
		}
	}
	return candidate
}

// majorityElement
// 直接排序返回中位数即为众数
//func majorityElement(nums []int) int {
//	sort.Ints(nums)
//	return nums[len(nums)/2]
//}
